/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package Project2.cs342.project1.mathNotebook.data;


import java.math.*;
import java.io.*;
import java.security.*;
import java.security.spec.*;


/**
 *
 * @author bosmak40
 */
public class RSAKeyGenerator {

    private byte[] publicKey;
    private byte[] privateKey;
    char[] charBank = {'a', 'b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z','0','1','2','3','4','5','6','7','8','9'};


    public RSAKeyGenerator(){

        publicKey = null;
        privateKey = null;

    }

    /**
     * Generates RSA keys from a randomly created string.
     *
     */
    public void generateKeys(){
        String randomString = "";
        int randomIndex = 0;
        for(int i = 0; i < 25; i++){
            randomIndex = (int)((charBank.length-1) * Math.random());
            randomString = randomString + charBank[randomIndex];
        }
        System.out.println("RANDOM STRING: " + randomString);
        getKeysFromSeed(randomString);

    }

    /**
     * Generates RSA keys as byte arrays using a String as a seed
     *
     * @param String seed
     */
    private void getKeysFromSeed(String seed){
        try{
            KeyPairGenerator keygenerator = KeyPairGenerator.getInstance ("rsa");
            SecureRandom secureSeed = SecureRandom.getInstance ("SHA1PRNG");

            byte [] keyData = seed.getBytes();
            secureSeed. setSeed ( keyData );
            keygenerator.initialize(512, secureSeed);
            KeyPair pair = keygenerator.generateKeyPair();
            PrivateKey priKey = pair.getPrivate();
            PublicKey pubKey = pair.getPublic();
            privateKey = priKey.getEncoded();
            publicKey = pubKey.getEncoded();

        }
        catch(java.security.NoSuchAlgorithmException e){
            System .out . println (" Exception : "+e);
        }

    }

    /**
     * Returns the public RSA key as a byte[]
     *
     * @return Public RSA key as a byte[]
     */
    public byte[] getPublicKey(){
        return publicKey;
    }

    /**
     * Returns the private RSA key as a byte[]
     *
     * @return Private RSA key as a byte[]
     */
    public byte[] getPrivateKey(){
        return privateKey;
    }
}
